<?php
/**
 * Created by PhpStorm.
 * User: jerrygo
 * Date: 19-5-22
 * Time: 下午11:47
 */

namespace frontend\models;


use common\components\SmsCaptcha\CaptchaValidator;
use common\models\c2\entity\FeUser;
use common\models\c2\entity\FeUserModel;
use cza\base\models\ModelTrait;
use Yii;
use yii\base\Model;

class ForgetPasswordForm extends Model
{
    use ModelTrait;

    public $mobile_number;
    public $password;
    public $password_twice;
    public $verify_code;

    public function rules()
    {
        return [
            [['mobile_number',], 'match', 'pattern' => '/^1[0-9]{10}$/', 'message' => Yii::t('app.c2', '{attribute} must be mobile format!')],
            [['mobile_number'], 'string', 'length' => 11],
            [['mobile_number'], 'number', 'integerOnly' => true],
            [['mobile_number'], 'required',],
            [['mobile_number'], 'validateMobileNumber',],
            [['password', 'password_twice',], 'string', 'min' => 6],
            ['password_twice', 'compare', 'compareAttribute' => 'password'],
            ['verify_code', CaptchaValidator::className()],
        ]; // TODO: Change the autogenerated stub
    }

    public function attributeLabels()
    {
        return [
            'mobile_number' => Yii::t('app.c2', 'Mobile Number'),
            'password'=> Yii::t('app.c2', 'Password'),
            'password_twice'=> Yii::t('app.c2', 'Password Twice'),
            'verify_code' => Yii::t('app.c2', 'Verification Code'),
        ]; // TODO: Change the autogenerated stub
    }

    public function validateMobileNumber($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = FeUser::findByMobileNumber($this->mobile_number);
            if (is_null($user)) {
                $this->addError($attribute, Yii::t('app.c2', 'Incorrect mobile number.'));
            }
        }
    }

    public function save()
    {
        Yii::info($this->mobile_number);
        $user = FeUser::findByMobileNumber($this->mobile_number);
        Yii::info($user);
        $user->setPassword($this->password);
        $user->generateAuthKey();
        return $user->save() ? $user : null;
    }

}